
package me.zhengjie.service.impl;

import me.zhengjie.domain.AppWork;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.service.dto.AppEventQueryCriteria;
import me.zhengjie.service.mapstruct.ApiWorkMapper;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.AppWorkRepository;
import me.zhengjie.service.AppWorkService;
import me.zhengjie.service.dto.AppWorkDto;
import me.zhengjie.service.dto.AppWorkQueryCriteria;
import me.zhengjie.service.mapstruct.AppWorkMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author IQW
* @date 2022-07-03
**/
@Service
@RequiredArgsConstructor
public class AppWorkServiceImpl implements AppWorkService {

    private final AppWorkRepository appWorkRepository;
    private final AppWorkMapper appWorkMapper;
    private final ApiWorkMapper apiWorkMapper;
    private final UserService userService;
    private final RoleService roleService;

    @Override
    public Map<String,Object> queryAll(AppWorkQueryCriteria criteria, Pageable pageable){

        //获取最小权限
        Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
        System.out.println("min level:"+currentLevel);
        if(currentLevel<=2){
            //管理员查看所有
        }else{
            //查看当前责任区
            Long userId = SecurityUtils.getCurrentUserId();
            UserDto user = userService.findById(userId);
            criteria.setAreaId(user.getAreaId());
        }
        if(!StringUtils.isEmpty(criteria.getNickName())){
            //查询出巡护人userId
            UserDto userCheck = userService.findByNickName(criteria.getNickName().trim());
            if(null != userCheck){
                criteria.setUserId(userCheck.getId().intValue());
            }else{
                criteria.setUserId(-1);
            }
            criteria.setNickName(null);
        }
        Page<AppWork> page = appWorkRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);

        Page<AppWorkDto> page2 = page.map(appWorkMapper::toDto);
        //查询用户信息
        page2.getContent().forEach(appWorkDto -> {
            UserDto user = userService.findById(appWorkDto.getUserId());
            if(null!=user){
                appWorkDto.setNickName(user.getNickName());
                appWorkDto.setAvatarPath(StringUtils.getUserHead(user.getAvatarPath()));
                appWorkDto.setWorkNo(user.getWorkNo());
            }
        });
        return PageUtil.toPages(page2,"");
    }

    @Override
    public Map<String,Object> queryAllApi(AppWorkQueryCriteria criteria, Pageable pageable){
        Page<AppWork> page = appWorkRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPages(page.map(apiWorkMapper::toDto),"");
    }

    @Override
    public List<AppWorkDto> queryAll(AppWorkQueryCriteria criteria){
        return appWorkMapper.toDto(appWorkRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public float selWorkMilesSum(Integer userId) {
        return appWorkRepository.selWorkMilesSum(userId);
    }

    @Override
    public List<AppWorkDto> queryAllIndex(Integer userId){

        AppWorkQueryCriteria criteria = new AppWorkQueryCriteria();
        criteria.setUserId(userId);
        criteria.setStatus(0);
        criteria.setJjcd("3");
        return appWorkMapper.toDto(appWorkRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public Integer selectWorking(Integer userId){

        AppWorkQueryCriteria criteria = new AppWorkQueryCriteria();
        criteria.setUserId(userId);
        criteria.setStatus(1);
        List<AppWorkDto> list = queryAll(criteria);
        if(null != list && list.size()>0){
            return list.get(0).getWorkId();
        }else{
            return 0;
        }
    }

    @Override
    public Integer selUndoWorkCount(Integer userId){

        AppWorkQueryCriteria criteria = new AppWorkQueryCriteria();
        criteria.setUserId(userId);
        criteria.setStatusLessTh(1); //0或1
        List<AppWorkDto> list = queryAll(criteria);
        return list.size();
    }

    @Override
    public Integer selWorkCount(Integer userId){

        AppWorkQueryCriteria criteria = new AppWorkQueryCriteria();
        criteria.setUserId(userId);
        criteria.setStatus(2);
        List<AppWorkDto> list = queryAll(criteria);
        return list.size();
    }

    @Override
    @Transactional
    public AppWorkDto findById(Integer workId) {
        AppWork appWork = appWorkRepository.findById(workId).orElseGet(AppWork::new);
        ValidationUtil.isNull(appWork.getWorkId(),"AppWork","workId",workId);
        return appWorkMapper.toDto(appWork);
    }

    @Override
    @Transactional
    public AppWork findOne(Integer workId) {
        return appWorkRepository.findById(workId).orElseGet(AppWork::new);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppWorkDto create(AppWork resources) {
        return appWorkMapper.toDto(appWorkRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AppWork resources) {
        AppWork appWork = appWorkRepository.findById(resources.getWorkId()).orElseGet(AppWork::new);
        ValidationUtil.isNull( appWork.getWorkId(),"AppWork","id",resources.getWorkId());
        appWork.copy(resources);
        appWorkRepository.save(appWork);
    }

    @Override
    public void updateStatus(Integer workId, Integer status,boolean isRest) {
        if(isRest){
            appWorkRepository.reSetStatus(workId,status);
        }else{
            appWorkRepository.updateStatus(workId,status);
        }
    }

    @Override
    @Transactional
    public Integer selWorkInt(Integer userId) {
        return appWorkRepository.selWorkInt(userId);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer workId : ids) {
            appWorkRepository.deleteById(workId);
        }
    }

    @Override
    @Transactional
    public Boolean setWorkExp() {
        appWorkRepository.setWorkExp(DateUtils.getNowTimestamp());
        return true;
    }

    @Override
    public void download(List<AppWorkDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AppWorkDto appWork : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("分配用户ID", appWork.getUserId());
            map.put("标题", appWork.getTitle());
            map.put("类型（1临时巡护，2日常巡护，3紧急巡护）", appWork.getType());
            map.put("目的地", appWork.getAddress());
            map.put("目的地经度", appWork.getLon());
            map.put("目的地纬度", appWork.getLat());
            map.put("已行驶时长（秒）", appWork.getWorkTime());
            map.put("已行驶里程（米）", appWork.getWorkMile());
            map.put("巡护开始时间", appWork.getStartTime());
            map.put("巡护结束时间", appWork.getEndTime());
            map.put("状态（0未开始，1巡护中，2已完成）", appWork.getStatus());
            map.put("创建日期", appWork.getCreateTime());
            map.put("更新日期", appWork.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}